const FIRST_MENU = 'firstMenu'
const TOKEN = 'token'
const USRE_INFO = 'userInfo'
const USER_MENU = 'userMenus'

const ALL_DEPARTMENT_LIST = 'all_department_list'

const ALL_ROLE_LIST = 'all_role_list'

const ALL_MENU_LIST = 'all_menu_list'

class Localcache {
  private saveCache(key: string, value: any = '') {
    if (value) {
      try {
        const result = JSON.stringify(value)
        window.localStorage.setItem(key, result)
      } catch (error) {
        console.log('保存失败,key=', key)
      }
    }
  }

  private getCache(key: string): any {
    const result: string | null = window.localStorage.getItem(key)
    if (result) {
      try {
        return JSON.parse(result)
      } catch (error) {
        console.log('获取失败,key=', key)
        return ''
      }
    } else {
      return ''
    }
  }

  private deleteCache(key: string) {
    window.localStorage.removeItem(key)
  }

  /**
   * 1:清空所有缓存，慎用!!!!
   */
  public clearCache() {
    window.localStorage.clear()
  }

  /**
   * 2:保存用户第一个菜单
   * @param menu
   */
  public saveFirstMenu(menu: any) {
    this.saveCache(FIRST_MENU, menu)
  }
  public getFirstMenu() {
    return this.getCache(FIRST_MENU)
  }
  public delteFirstMenu() {
    this.deleteCache(FIRST_MENU)
  }

  /**
   * 3:保存用户token
   * @param token
   */
  public saveToken(token: string) {
    this.saveCache(TOKEN, token)
  }

  public getToken() {
    return this.getCache(TOKEN)
  }
  public delteToken() {
    this.deleteCache(TOKEN)
  }

  /**
   * 4:保存用户信息
   * @param info
   */
  public saveUserInfo(info: any) {
    this.saveCache(USRE_INFO, info)
  }

  public getUserInfo() {
    return this.getCache(USRE_INFO)
  }

  public delteUserInfo() {
    this.deleteCache(USRE_INFO)
  }

  /**
   * 5:保存用户菜单列表
   * @param menus
   */
  public saveUserMenu(menus: any) {
    this.saveCache(USER_MENU, menus)
  }

  public getUserMenu() {
    return this.getCache(USER_MENU)
  }

  public delteUserMenu() {
    this.deleteCache(USER_MENU)
  }

  public saveAllDepartList(list: any) {
    this.saveCache(ALL_DEPARTMENT_LIST, list)
  }

  public getAllDepartList() {
    return this.getCache(ALL_DEPARTMENT_LIST)
  }

  public deleteAllDepartList() {
    this.deleteCache(ALL_DEPARTMENT_LIST)
  }

  public saveAllRoleList(list: any) {
    this.saveCache(ALL_ROLE_LIST, list)
  }

  public getAllRoleList() {
    return this.getCache(ALL_ROLE_LIST)
  }

  public deleteAllRoleList() {
    this.deleteCache(ALL_ROLE_LIST)
  }

  public saveAllMenuList(list: any) {
    this.saveCache(ALL_MENU_LIST, list)
  }

  public getAllMenuList() {
    return this.getCache(ALL_MENU_LIST)
  }

  public deleteAllMenuList() {
    this.deleteCache(ALL_MENU_LIST)
  }
}

export default new Localcache()
